package servlets;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.logging.Level;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.Request;

import com.sun.istack.internal.logging.Logger;

import dal.Crud;

import utils.CertGen;

/**
 * Servlet implementation class DownloadCSRServlet
 */
@WebServlet("/DownloadCSRServlet")
public class DownloadCSRServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DownloadCSRServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getSession().getAttribute("userId") != null) {
			String filename = request.getParameter("filename");
			String action = request.getParameter("action");

			if (filename != null) {

				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + filename);

				switch (action) {
				case "CSRGEN":
					downloadCSRGen(response, filename);
					break;
				case "CACERT":
					downloadCaCert(response, filename);
					
				case "GETCERT":
					downloadUserCert(request,response, filename);

				}
			}

		} else {
			response.getOutputStream().write("Access denied.".getBytes());
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	private void downloadCSRGen(HttpServletResponse response, String filename)
			throws IOException {
		File file = new File(getServletContext()
				.getRealPath("/res/" + filename));
		Path path = Paths.get(file.getPath());

		byte[] bytes = Files.readAllBytes(path);

		response.getOutputStream().write(bytes);
	}

	private void downloadCaCert(HttpServletResponse response, String filename) {
		try {
			Crud crud = new Crud();
			String certStr = crud.getCACertificate();
			X509Certificate cert = CertGen.getCertifcate(certStr);
			ByteArrayOutputStream out = CertGen.encode(cert);
			response.getOutputStream().write(out.toByteArray());

		} catch (Exception e) {
			Logger.getLogger(this.getClass()).log(Level.SEVERE, e.toString());
		}
	}
	
	private void downloadUserCert(HttpServletRequest request, HttpServletResponse response, String filename) {
		try {
			Crud crud = new Crud();
			int csrId = Integer.parseInt(request.getParameter("csrId"));
			int userId = (int) request.getSession().getAttribute("userId");
			String certStr = crud.getUserCertificate(userId, csrId);
			X509Certificate cert = CertGen.getCertifcate(certStr);
			ByteArrayOutputStream out = CertGen.encode(cert);
			response.getOutputStream().write(out.toByteArray());

		} catch (Exception e) {
			Logger.getLogger(this.getClass()).log(Level.SEVERE, e.toString());
		}
	}

}
